package com.example.bingobox.ui.home;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.provider.Settings;
import android.content.Intent;
import android.text.format.DateFormat;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.bingobox.data.DataInitializer;
import com.example.bingobox.data.model.State;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.example.bingobox.databinding.FragmentHomeBinding;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private ActivityResultLauncher<String> requestPermissionLauncher;
    private ActivityResultLauncher<Intent> manageStoragePermissionLauncher;
    private Gson gson;
    private DataInitializer dataInitializer;
    private HomeViewModel homeViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        gson = new GsonBuilder().setPrettyPrinting().create();
        dataInitializer = new DataInitializer(requireContext());
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);

        // 创建通知渠道
        createNotificationChannel();

        // 初始化权限请求
        requestPermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        checkManageStoragePermission();
                    } else {
                        Toast.makeText(getContext(), "需要存储权限", Toast.LENGTH_LONG).show();
                    }
                }
        );

        // 初始化管理存储权限请求
        manageStoragePermissionLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (Environment.isExternalStorageManager()) {
                        initDataFiles();
                        initLocationService();
                    } else {
                        Toast.makeText(getContext(), "需要文件管理权限", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 检查存储权限
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
            intent.setData(uri);
            manageStoragePermissionLauncher.launch(intent);
        } else {
            initDataFiles();
            initLocationService();
        }
        
        // 设置重抽按钮点击事件
        binding.btnRedraw.setOnClickListener(v -> homeViewModel.drawRandomTask());

        // 观察当前任务的变化
        homeViewModel.getCurrentTask().observe(getViewLifecycleOwner(), task -> {
            if (task != null) {
                binding.taskTitle.setText(task.getName());
                binding.taskDescription.setText(task.getDescription());
                if (task.getDeadline() != 0) {
                    String deadline = DateFormat.format("yyyy-MM-dd HH:mm", new Date(task.getDeadline())).toString();
                    binding.taskDeadline.setText("截止时间: " + deadline);
                } else {
                    binding.taskDeadline.setText("");
                }
            } else {
                binding.taskTitle.setText("暂无任务");
                binding.taskDescription.setText("");
                binding.taskDeadline.setText("");
            }
        });
    }

    private void checkManageStoragePermission() {
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
            intent.setData(uri);
            manageStoragePermissionLauncher.launch(intent);
        } else {
            initDataFiles();
            initLocationService();
        }
    }

    // 初始化所有数据文件
    private void initDataFiles() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        if (!dataDir.exists() && !dataDir.mkdirs()) {
            Toast.makeText(requireContext(), "创建数据目录失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 使用 DataInitializer 初始化所有数据文件
        dataInitializer.initStateFile(dataDir);
        dataInitializer.initTodoboxFile(dataDir);
    }

    private void initLocationService() {
        try {
            AMapLocationClient.updatePrivacyShow(requireContext(), true, true);
            AMapLocationClient.updatePrivacyAgree(requireContext(), true);
            AMapLocationClient locationClient = new AMapLocationClient(requireContext());
            
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            locationClient.setLocationOption(option);

            locationClient.setLocationListener(aMapLocation -> {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    State.Location location = new State.Location(
                        aMapLocation.getCity(),
                        aMapLocation.getLatitude(),
                        aMapLocation.getLongitude()
                    );
                    State state = new State();
                    state.setCurrentCity(location);
                    state.setCurrentLocation(location);
                    
                    // 保存状态
                    saveState(state);
                }
            });

            locationClient.startLocation();
        } catch (Exception e) {
            Toast.makeText(requireContext(), "初始化位置服务失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveState(State state) {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File stateFile = new File(dataDir, "state.json");
        
        try (FileWriter writer = new FileWriter(stateFile)) {
            String json = gson.toJson(state);
            writer.write(json);
        } catch (IOException e) {
            if (getContext() != null) {
                Toast.makeText(getContext(), "保存状态失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void createNotificationChannel() {
        // Implementation of createNotificationChannel method
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}